package middleware

import (
	"math"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
)

func LoggerMiddleware(logg log.FieldLogger) gin.HandlerFunc {
	return func(c *gin.Context) {
		req := c.Request
		writer := c.Writer
		begin := time.Now()
		c.Next()
		end := time.Since(begin)
		reply := int(math.Ceil(float64(end.Nanoseconds()) / 1000000.0))
		latency := strconv.Itoa(reply) + "ms"

		logFields := log.Fields{
			"statusCode": writer.Status(),
			"latency":    latency,
			"userAgent":  req.UserAgent(),
			"method":     c.Request.Method,
			"path":       c.Request.URL.Path,
			"reply":      reply,
		}
		entry := logg.WithFields(logFields)

		if len(c.Errors) > 0 {
			entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())
		} else {
			if writer.Status() > 499 {
				entry.Error("")
			} else if writer.Status() > 399 {
				entry.Warn("")
			} else if reply >= 1000 {
				entry.Warn(logFields)
			}
		}
	}
}
